package databaseVersionControl.domain.db;

import java.util.ArrayList;
import java.util.List;

import databaseVersionControl.domain.dialect.Dialect;

public class Table implements TableComponent {
	
	private String name;
	private List<Column> columns = new ArrayList<Column>();
	
	public Table(String name) {
		this.name = name.toUpperCase();
	}
	
	public String getName() {
		return name;
	}

	public TableComponent defineColumns(Column... columns) {
		for (Column column : columns) addColumn(column);
		return this;
	}

	public Table addColumn(Column column) {
		columns.add(column);
		return this;
	}

	private boolean isLastColumn(Column column) {
		return column.equals( columns.get(columns.size() - 1) );
	}
		
	@Override
	public String sqlInDialect(Dialect dialect) {
		StringBuilder stringBuilder = new StringBuilder("TABLE ");
		stringBuilder.append(name);
		stringBuilder.append("(");
		
		for (Column column : columns) {
			stringBuilder.append(column.sqlInDialect(dialect));
			if ( !isLastColumn(column) ) stringBuilder.append(", ");
		}
		
		stringBuilder.append(");");
		
		return stringBuilder.toString();
	}

	@Override
	public String sqlIdentifier() {
		return "TABLE " + getName();
	}

	
}